package com.may.wlrj.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.prefs.Preferences;

import org.apache.log4j.Logger;

import com.may.wlrj.services.CircleService;

import de.schlichtherle.license.CipherParam;
import de.schlichtherle.license.DefaultCipherParam;
import de.schlichtherle.license.DefaultKeyStoreParam;
import de.schlichtherle.license.DefaultLicenseParam;
import de.schlichtherle.license.KeyStoreParam;
import de.schlichtherle.license.LicenseContent;
import de.schlichtherle.license.LicenseContentException;
import de.schlichtherle.license.LicenseManager;
import de.schlichtherle.license.LicenseParam;

public class VerifyLicense {
	private Logger log = Logger.getLogger(VerifyLicense.class);
	//common param
	private static String PUBLICALIAS = "";
	private static String STOREPWD = "";
	private static String SUBJECT = "";
	private static String licPath = "";
	private static String pubPath = "";
	private static String webRootPath = CircleService.class.getResource("").getPath().replaceFirst("/", "");
	private static String webInfPath = webRootPath.substring(0,webRootPath.indexOf("classes"));
	
	public void setParam(String propertiesPath) {
		// 获取参数
		Properties prop = new Properties();
		InputStream in = VerifyLicense.class.getClassLoader().getResourceAsStream(propertiesPath);
		try {
			prop.load(in);
		} catch (IOException e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
		PUBLICALIAS = prop.getProperty("PUBLICALIAS");
		STOREPWD = prop.getProperty("STOREPWD");
		SUBJECT = prop.getProperty("SUBJECT");
		licPath = prop.getProperty("licPath");
		pubPath = prop.getProperty("pubPath");
	}

	public boolean verify(Date lastdate) {		
		//验证服务器日期
		if(differentDays(lastdate,new Date()) < 0){
			System.out.println("服务器日期异常,请同步服务器日期.....!");
			log.error("服务器日期异常,请同步服务器日期.....!");
			XinLongUtil.xinLongUtil.setLicensedays(0);
			return false;
		}
		LicenseManager licenseManager = LicenseManagerHolder
				.getLicenseManager(initLicenseParams());
		// 安装证书
		try {
			
			licenseManager.install(new File(webInfPath + licPath));
			System.out.println("安装证书成功!");
			log.info("安装证书成功!");
		}catch(LicenseContentException lce){
			log.info("证书安装失败!===证书已过期!");
			XinLongUtil.xinLongUtil.setLicensedays(0);
		}catch (Exception e) {
			e.printStackTrace();
			log.info("证书安装失败!===" + e.getMessage());
			System.out.println("证书安装失败!");
			return false;
		}
		// 验证证书
		try {
			LicenseContent content =licenseManager.verify();
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Date notafter = content.getNotAfter();
			int leftdays = differentDays(new Date(),notafter);
			XinLongUtil.xinLongUtil.setLicensedays(leftdays);
			XinLongUtil.xinLongUtil.setLicensedate(format.format(notafter));
			log.info("验证证书成功!");
			System.out.println("验证证书成功!");
		}catch(LicenseContentException lce){
			log.info("证书验证失败!===证书已过期!");
			XinLongUtil.xinLongUtil.setLicensedays(0);
		} catch (Exception e) {
			e.printStackTrace();
			XinLongUtil.xinLongUtil.setLicensedays(-365);
			log.info("证书验证失败!===" + e.getMessage());
			System.out.println("证书验证失效!");
			return false;
		}
		return true;
	}

	// 返回验证证书需要的参数
	private static LicenseParam initLicenseParams() {
		Preferences preference = Preferences
				.userNodeForPackage(VerifyLicense.class);
		CipherParam cipherParam = new DefaultCipherParam(STOREPWD);

		KeyStoreParam privateStoreParam = new DefaultKeyStoreParam(
				VerifyLicense.class, pubPath, PUBLICALIAS, STOREPWD, null);
		LicenseParam licenseParams = new DefaultLicenseParam(SUBJECT,
				preference, privateStoreParam, cipherParam);
		return licenseParams;
	}
	
	/**
     * date2比date1多的天数
     * @param date1    
     * @param date2
     * @return    
     */
    public static int differentDays(Date date1,Date date2)
    {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);
        
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2)   //不同一年
        {
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++)
            {
                if(i%4==0 && i%100!=0 || i%400==0)    //闰年            
                {
                    timeDistance += 366;
                }
                else    //不是闰年
                {
                    timeDistance += 365;
                }
            }
            
            return timeDistance + (day2-day1) ;
        }
        else    //同一年
        {
            System.out.println("判断day2 - day1 : " + (day2-day1));
            return day2-day1;
        }
    }
}
